<template>
  <MainLayout>
    <view class="page">
      <!-- 顶部导航栏 -->
      <view class="header">
        <image class="back-icon" src="/static/icons/normalReturn.svg" @click="goBack"></image>
        <text class="header-title">草本评论区</text>
        <!-- 更多按钮 -->
        <image 
          v-if="post && (isAdmin || isOwner)" 
          class="more-icon" 
          src="/static/icons/delect/edit/more_detail.svg" 
          @click="showActionSheet">
        </image>
      </view>

      <!-- 帖子内容卡片 -->
      <view class="post-card" v-if="post">
        <!-- 作者信息 -->
        <view class="post-header">
          <view class="avatar">
            <!-- 可以替换为用户头像图片 -->
            <text class="avatar-text">{{ getAvatarText(post.userNickname) }}</text>
          </view>
          <view class="user-info">
            <text class="username">{{ post.userNickname || '未知用户' }}</text>
            <text class="post-time">{{ formatDate(post.publishTime) }}</text>
          </view>
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
          <text class="post-title">{{ post.title }}</text>
          <text class="post-text" v-if="post.content">{{ post.content }}</text>
        </view>

        <!-- 帖子图片 -->
        <view class="post-images" v-if="postImages.length > 0">
          <view class="image-grid" :class="{ 'single-image': postImages.length === 1 }">
            <image 
              v-for="(imageUrl, index) in postImages" 
              :key="index"
              :src="imageUrl" 
              class="post-image"
              mode="aspectFill"
              @click="previewImage(index, postImages)"
            />
          </view>
        </view>

        <!-- 互动数据 -->
        <view class="post-stats">
          <view class="stat-item" @click="handleLike">
            <span class="iconify stat-icon" :data-icon="isLiked ? 'mdi:thumb-up' : 'mdi:thumb-up-outline'"></span>
            <text>{{ post.likeCount }}</text>
          </view>
          <view class="stat-item">
            <span class="iconify stat-icon" data-icon="mdi:comment-outline"></span>
            <text>{{ post.replyCount }}</text>
          </view>
        </view>
      </view>

      <!-- 楼层和评论区 -->
      <view class="comments-section" v-if="post">
        <text class="comments-title">评论区</text>
        
        <!-- 楼层列表 -->
        <view class="floors-container">
          <view v-for="floor in floors" :key="floor.floorId" class="floor-item">
            <!-- 楼层信息 -->
            <view class="floor-header">
              <view class="avatar">
                <text class="avatar-text">{{ getAvatarText(floor.userNickname) }}</text>
              </view>
              <view class="user-info">
                <text class="username">{{ floor.userNickname || '未知用户' }}</text>
                <text class="post-time">{{ formatDate(floor.publishTime) }}</text>
              </view>
            </view>
            
            <!-- 楼层内容 -->
            <view class="floor-content">
              <text class="floor-text">{{ floor.content }}</text>
            </view>
            
            <!-- 楼层图片 -->
            <view class="floor-images" v-if="floor.images && floor.images.length > 0">
              <view class="image-grid" :class="{ 'single-image': floor.images.length === 1 }">
                <image 
                  v-for="(imageUrl, index) in floor.images" 
                  :key="index"
                  :src="imageUrl" 
                  class="floor-image"
                  mode="aspectFill"
                  @click="previewImage(index, floor.images)"
                />
              </view>
            </view>
            
            <!-- 楼层评论 -->
            <view class="comments-container">
              <view 
                v-for="comment in floorComments[floor.floorId]" 
                :key="comment.commentId" 
                class="comment-item"
                @click="replyToComment(comment, floor)"
              >
                <view class="comment-header">
                  <view class="avatar small">
                    <text class="avatar-text small">{{ getAvatarText(comment.userNickname) }}</text>
                  </view>
                  <view class="user-info">
                    <text class="username">{{ comment.userNickname || '未知用户' }}</text>
                    <text class="post-time">{{ formatDate(comment.publishTime) }}</text>
                  </view>
                </view>
                <view class="comment-content">
                  <text class="comment-text">
                    <text v-if="comment.parentCommentId !== 0">@{{ comment.parentCommentNickname }} </text>
                    {{ comment.content }}
                  </text>
                </view>
              </view>
              
              <!-- 添加评论按钮 -->
              <view class="add-comment-btn" @click="addComment(floor)">
                <text>回复</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 无评论提示 -->
        <view class="comment-placeholder" v-if="floors.length === 0">
          <text>暂无评论，快来抢沙发~</text>
        </view>
      </view>

      <!-- 加载中状态 -->
      <view class="loading" v-else>
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <!-- 底部输入框 -->
      <view class="input-section">
        <input 
          class="input-field" 
          v-model="inputContent" 
          :placeholder="currentReply.targetType === 'floor' ? '发表新楼层...' : '发表评论...'"
          @confirm="handlePublish"
        />
        <button class="publish-btn" @click="handlePublish">发送</button>
      </view>
      
      <!-- 回复提示 -->
      <view v-if="currentReply.targetType !== 'floor'" class="reply-tip">
        <text>正在回复 @{{ currentReply.targetNickname }}：</text>
        <text class="clear-reply" @click="clearReply">取消</text>
      </view>
    </view>
    
    <!-- 半模态弹窗 -->
    <view class="action-sheet" v-if="showActions" @click="hideActionSheet">
      <view class="action-sheet-content" @click.stop>
        <view class="action-sheet-item" @click="handleEdit">编辑</view>
        <view class="action-sheet-item delete" @click="handleDelete">删除</view>
        <view class="action-sheet-cancel" @click="hideActionSheet">取消</view>
      </view>
    </view>
  </MainLayout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import MainLayout from '../../layout/MainLayout.vue'
import postApi from '../../http/models/post'
import floorApi from '../../http/models/floor'
import commentApi from '../../http/models/comment'
import imageApi from '../../http/models/image'
import { onLoad } from '@dcloudio/uni-app'

const post = ref(null)
const postId = ref(0)
const isLiked = ref(false)
const floors = ref([])
const floorComments = reactive({})
const inputContent = ref('') // 输入框内容
const postImages = ref([]) // 帖子图片列表
const showActions = ref(false) // 控制半模态弹窗显示
const currentUser = ref(null) // 当前用户信息

// 当前回复的目标信息
const currentReply = reactive({
  targetType: 'floor', // 'floor' 或 'comment'
  targetId: null, // 楼层ID或评论ID
  targetNickname: '', // 目标用户昵称
  parentCommentId: 0 // 父评论ID，用于楼中楼
})

// 获取头像显示文字（取用户名首字母）
const getAvatarText = (nickname) => {
  if (!nickname) return '用'
  return nickname.charAt(0)
}

// 是否为管理员
const isAdmin = computed(() => {
  return currentUser.value && currentUser.value.ifAmdin === 1
})

// 是否为帖子所有者
const isOwner = computed(() => {
  return post.value && currentUser.value && post.value.userId === currentUser.value.userId
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 返回上一页
const goBack = () => {
  uni.switchTab({
    url: '/pages/chat/chat'
  })
}

// 显示操作菜单
const showActionSheet = () => {
  showActions.value = true
}

// 隐藏操作菜单
const hideActionSheet = () => {
  showActions.value = false
}

// 编辑帖子
const handleEdit = () => {
  hideActionSheet()
  // 这里可以添加编辑逻辑
  uni.showToast({
    title: '编辑功能待实现',
    icon: 'none'
  })
}

// 删除帖子
const handleDelete = async () => {
  hideActionSheet()
  
  // 确认删除
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个帖子吗？删除后无法恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await postApi.deletePost(postId.value)
          if (response.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          } else {
            uni.showToast({
              title: response.msg || '删除失败',
              icon: 'none'
            })
          }
        } catch (error) {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 处理点赞
const handleLike = () => {
  isLiked.value = !isLiked.value
  post.value.likeCount += isLiked.value ? 1 : -1
  // 实际项目中这里需要调用点赞接口
}

// 图片预览
const previewImage = (index, imageList) => {
  uni.previewImage({
    current: index,
    urls: imageList
  })
}

// 添加评论（点击回复按钮）
const addComment = (floor) => {
  currentReply.targetType = 'comment'
  currentReply.targetId = floor.floorId
  currentReply.targetNickname = ''
  currentReply.parentCommentId = 0
}

// 回复特定评论
const replyToComment = (comment, floor) => {
  currentReply.targetType = 'comment'
  currentReply.targetId = floor.floorId
  currentReply.targetNickname = comment.userNickname
  currentReply.parentCommentId = comment.commentId
}

// 清除回复状态
const clearReply = () => {
  currentReply.targetType = 'floor'
  currentReply.targetId = null
  currentReply.targetNickname = ''
  currentReply.parentCommentId = 0
}

// 发布内容
const handlePublish = async () => {
  if (!inputContent.value.trim()) {
    uni.showToast({
      title: '请输入内容',
      icon: 'none'
    })
    return
  }

  try {
    if (currentReply.targetType === 'floor') {
      // 发布新楼层
      const res = await floorApi.publishFloor({
        postId: postId.value,
        content: inputContent.value
      })

      if (res.code === 200) {
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        
        // 清空输入框
        inputContent.value = ''
        
        // 重新加载楼层数据
        await fetchFloors()
      } else {
        uni.showToast({
          title: res.msg || '发布失败',
          icon: 'none'
        })
      }
    } else {
      // 发布评论（楼中楼）
      const params = {
        floorId: currentReply.targetId,
        content: inputContent.value,
        parentCommentId: currentReply.parentCommentId
      }
      
      const res = await commentApi.publishComment(params)
      
      if (res.code === 200) {
        uni.showToast({
          title: '评论成功',
          icon: 'success'
        })
        
        // 清空输入框和回复状态
        inputContent.value = ''
        clearReply()
        
        // 重新加载楼层数据
        await fetchFloors()
      } else {
        uni.showToast({
          title: res.msg || '评论失败',
          icon: 'none'
        })
      }
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 获取帖子详情
const fetchPostDetail = async (imagesFromParent) => {
  try {
    const res = await postApi.getPostDetail(postId.value)
    if (res.code === 200) {
      post.value = res.data
      // 如果父页面传了图片数据则使用，否则重新获取
      if (imagesFromParent && imagesFromParent.length > 0) {
        postImages.value = imagesFromParent
      } else {
        // 获取帖子图片
        await fetchPostImages()
      }
      // 获取楼层信息
      await fetchFloors()
    } else {
      uni.showToast({
        title: res.msg || '获取失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

// 获取帖子图片
const fetchPostImages = async () => {
  try {
    const res = await imageApi.getTargetImages(postId.value, 0) // 0表示帖子类型
    if (res.code === 200) {
      postImages.value = res.data.imageUrls
    }
  } catch (error) {
    console.error('获取帖子图片失败:', error)
  }
}

// 获取帖子下的所有楼层
const fetchFloors = async () => {
  try {
    const res = await floorApi.getPostFloors(postId.value, 1, 100) // 获取前100个楼层
    if (res.code === 200) {
      floors.value = res.data.list
      
      // 获取每个楼层的评论和图片
      for (const floor of floors.value) {
        await fetchFloorComments(floor.floorId)
        await fetchFloorImages(floor)
      }
    } else {
      uni.showToast({
        title: res.msg || '获取楼层失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取楼层错误',
      icon: 'none'
    })
  }
}

// 获取楼层图片
const fetchFloorImages = async (floor) => {
  try {
    const res = await imageApi.getTargetImages(floor.floorId, 1) // 1表示楼层类型
    if (res.code === 200) {
      // 将图片列表添加到楼层对象中
      floor.images = res.data.imageUrls
    }
  } catch (error) {
    console.error('获取楼层图片失败:', error)
  }
}

// 获取楼层下的评论
const fetchFloorComments = async (floorId) => {
  try {
    const res = await commentApi.getFloorComments(floorId, 1, 100) // 获取前100个评论
    if (res.code === 200) {
      // 使用Vue的响应式系统确保floorComments是响应式的
      floorComments[floorId] = res.data.list
      
      // 为每个评论添加父评论用户昵称
      const comments = floorComments[floorId];
      const commentMap = {};
      comments.forEach(comment => {
        commentMap[comment.commentId] = comment;
      });
      
      comments.forEach(comment => {
        if (comment.parentCommentId !== 0 && commentMap[comment.parentCommentId]) {
          comment.parentCommentNickname = commentMap[comment.parentCommentId].userNickname;
        }
      });
    } else {
      uni.showToast({
        title: res.msg || '获取评论失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '获取评论错误',
      icon: 'none'
    })
  }
}

// 页面加载时获取参数
onLoad((options) => {
  if (options && options.postId) {
    postId.value = parseInt(options.postId)
    // 检查是否有从父页面传来的图片数据
    let imagesFromParent = []
    if (options.images) {
      try {
        imagesFromParent = JSON.parse(decodeURIComponent(options.images))
      } catch (e) {
        console.error('解析图片数据失败:', e)
      }
    }
    fetchPostDetail(imagesFromParent)
    
    // 获取当前用户信息
    getCurrentUser()
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      goBack()
    }, 1000)
  }
})

// 获取当前用户信息
const getCurrentUser = () => {
  // 这里应该根据实际项目情况获取当前用户信息
  // 示例代码，需要根据实际情况调整
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      currentUser.value = JSON.parse(userInfo)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}
</script>

<style scoped>
@import '../../components/scss/post-detail.css';

/* 更多按钮 */
.more-icon {
  width: 24px;
  height: 24px;
  margin-top: 50px;
}

/* 半模态弹窗 */
.action-sheet {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.action-sheet-content {
  background-color: #fff;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  padding: 15px;
}

.action-sheet-item {
  padding: 15px;
  text-align: center;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.action-sheet-item.delete {
  color: #ff4d4f;
}

.action-sheet-cancel {
  padding: 15px;
  text-align: center;
  font-size: 16px;
  color: #999;
  margin-top: 10px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

/* 回复相关样式 */
.add-comment-btn {
  padding: 10px;
  color: #007AFF;
  text-align: right;
  font-size: 14px;
}

.reply-tip {
  padding: 10px 15px;
  background-color: #f0f8ff;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}

.clear-reply {
  color: #007AFF;
}
</style>